package com.maibow.controller.admin;

import java.io.File;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.maibow.controller.base.BaseController;
import com.maibow.entity.Page;
import com.maibow.entity.admin.SysOperator;
import com.maibow.entity.admin.Version;
import com.maibow.service.admin.VersionService;
import com.maibow.service.system.CommonService;
import com.maibow.util.CommonConstants;
import com.maibow.util.DateUtil;
import com.maibow.util.FileUpload;
import com.maibow.util.PageData;
import com.maibow.util.PathUtil;

/**
 * 
 * 脉博网络后台管理系统
 * 包名：com.maibow.controller.admin
 * 文件名：NewRoleController.java
 * 作者: 吴比(Wubi)
 * 时间：2015年3月29日-上午10:09:51
 * Copyright@ 2015湖南脉博网络科技有限公司-版权所有
 *
 */
@Controller
@RequestMapping(value = "/version")
public class VersionController extends BaseController {

    @Resource(name = "versionService")
    private VersionService versionService;

    @Resource(name = "commonService")
    private CommonService commonService;

    /**
     * 
     * list(角色列表)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param page
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/list")
    public ModelAndView list(Page page) throws Exception {
        ModelAndView modelView = this.getModelAndView();

        SysOperator operator = commonService.getCurrentOperator();
        if (null == operator) {
            modelView.setViewName(this.getRequest().getContextPath() + CommonConstants.MAIN_LOGIN);
        }

        List<Version> versionList = versionService.listAllVersions();
        for (Version version : versionList) {
            version.setRelease_date_show(DateUtil.formatTimeDate(version.getRelease_date()));
        }

        modelView.addObject("versionList", versionList);
        modelView.setViewName("system/version/version_list");
        return modelView;
    }

    /**
     * 新增页面
     * 
     * @param page
     * @return
     */
    @RequestMapping(value = "/toAdd")
    public ModelAndView toAdd(Page page) {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();
            modelView.setViewName("system/version/version_add");
            modelView.addObject("pageData", pageData);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return modelView;
    }

    /**
     * 保存新增信息
     */
    @RequestMapping(value = "/addVersion", method = RequestMethod.POST)
    public ModelAndView addVersion(HttpServletRequest request, @RequestParam(required = false) MultipartFile url_android, @RequestParam(value = "version_name", required = false) String version_name,
                        @RequestParam(value = "version_code", required = false) String version_code, @RequestParam(value = "url", required = false) String url,
                        @RequestParam(value = "isactive", required = false) String isactive, @RequestParam(value = "type", required = false) String type,
                        @RequestParam(value = "force_upgrade", required = false) String force_upgrade, @RequestParam(value = "description", required = false) String description,
                        @RequestParam(value = "release_date", required = false) String release_date) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        try {
            Version version = new Version();
            version.setVersion_name(version_name);
            version.setVersion_code(Integer.valueOf(version_code));
            version.setUrl(url);
            version.setType(Integer.valueOf(type));
            version.setForce_upgrade(Integer.valueOf(force_upgrade));
            version.setIsactive(Integer.valueOf(isactive));
            version.setDescription(description);
            version.setRelease_date(DateUtil.getDateByStr(release_date));

            String ffile = DateUtil.getDays(), fileName = "";
            String filePath = null;

            if (null != url_android && !url_android.isEmpty()) {
                filePath = PathUtil.getUploadImagePath() + CommonConstants.FILEPATHFILE + ffile + "_version/"; // 文件上传路径
                fileName = FileUpload.fileUp(url_android, filePath, this.get32UUID()); // 执行上传
                String imageurlstr = CommonConstants.FILEPATHFILE + ffile + "_version/" + fileName;
                version.setUrl(imageurlstr);
            }

            versionService.addVersion(version);
            modelView.addObject("msg", "success");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            modelView.addObject("msg", "failed");
        }
        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 编辑页面
     * 
     * @param version_id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/toEdit")
    public ModelAndView toEdit(String version_id) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();
            pageData.put("version_id", Integer.valueOf(version_id));
            Version version = versionService.findVersionById(pageData);
            version.setRelease_date_show(DateUtil.formatTimeDate(version.getRelease_date()));
            modelView.setViewName("system/version/version_edit");
            modelView.addObject("version", version);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return modelView;
    }

    /**
     * 编辑页面
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editVersion")
    public ModelAndView edit(HttpServletRequest request, @RequestParam(required = false) MultipartFile url_android, @RequestParam(value = "version_id", required = false) String version_id,
                        @RequestParam(value = "version_name", required = false) String version_name, @RequestParam(value = "version_code", required = false) String version_code,
                        @RequestParam(value = "url", required = false) String url, @RequestParam(value = "url2", required = false) String url2,
                        @RequestParam(value = "url3", required = false) String url3, @RequestParam(value = "androidurlhidden", required = false) String androidurlhidden,
                        @RequestParam(value = "isactive", required = false) String isactive, @RequestParam(value = "type", required = false) String type,
                        @RequestParam(value = "force_upgrade", required = false) String force_upgrade, @RequestParam(value = "description", required = false) String description,
                        @RequestParam(value = "release_date", required = false) String release_date) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        try {
            Version version = new Version();
            version.setVersion_id(Integer.valueOf(version_id));
            version.setVersion_name(version_name);
            version.setVersion_code(Integer.valueOf(version_code));
            version.setUrl(url);
            version.setUrl2(url2);
            version.setUrl3(url3);
            // version.setType(Integer.valueOf(type));
            version.setForce_upgrade(Integer.valueOf(force_upgrade));
            version.setIsactive(Integer.valueOf(isactive));
            version.setDescription(description);
            version.setRelease_date(DateUtil.getDateByStr(release_date));

            String ffile = DateUtil.getDays(), fileName = "";
            String filePath = null;

            if (null != url_android && !url_android.isEmpty()) {
                filePath = PathUtil.getUploadImagePath() + CommonConstants.FILEPATHFILE + ffile + "_version/"; // 文件上传路径
                fileName = FileUpload.fileUp(url_android, filePath, this.get32UUID()); // 执行上传
                String imageurlstr = CommonConstants.FILEPATHFILE + ffile + "_version/" + fileName;
                version.setUrl(imageurlstr);
            } else {
                if (null != androidurlhidden && !"".equals(androidurlhidden)) {
                    version.setUrl(androidurlhidden);
                }
            }
            versionService.editVersion(version);
            modelView.addObject("msg", "success");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            modelView.addObject("msg", "failed");
        }
        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 删除文件
     * deltp(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param url1
     * 标记：@param url2
     * 标记：@param url3
     * 标记：@param tpurl
     * 标记：@param version_id
     * 标记：@param request
     * 标记：@param response
     * 标记：@return
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @ResponseBody
    @RequestMapping(value = "/deltp/{url1}/{url2}/{url3}/{tpurl}/{version_id}", method = RequestMethod.POST)
    public ModelAndView deltp(@PathVariable String url1, @PathVariable String url2, @PathVariable String url3, @PathVariable String tpurl, @PathVariable String version_id, HttpServletRequest request,
                        HttpServletResponse response) {
        logBefore(logger, "删除图片");
        ModelAndView modelView = new ModelAndView();
        String msg = null;
        try {
            PageData pageData = new PageData();
            pageData = this.getPageData();
            pageData.put("version_id", Integer.valueOf(version_id));

            // 图片路径
            if (tpurl != null) {
                // 删除硬盘上的文件 start
                String xmpath = PathUtil.getUploadImagePath(); // 项目路径
                tpurl = xmpath.trim() + url1 + "/" + url2 + "/" + url3 + "/" + tpurl;

                // 'file:/'
                File f = new File(tpurl.trim());
                if (f.exists()) {
                    f.delete();
                } else {
                    logger.debug("文件不存在");
                }
                // 删除硬盘上的文件 end
                versionService.delTp(pageData); // 删除数据中图片数据
            }

            msg = "success";
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

        modelView.addObject(msg);
        return modelView;
    }
}
